<?php
namespace App\HttpController\Api;

use App\Think\Config;
use App\Think\Db;
use App\Model\Trade as TradeModel;

/**
 * 交易接口Trade
 */
class Trade extends ApiBase
{
    protected $noNeedLogin = ['amount_list'];

    /**
     * 交易记录查询
     * @param string $starttime 开始时间|格式2020-01-01
     * @param string $endtime   结束时间|格式2020-01-01
     * @param string $type  交易类型|可选|:recharge=充值,cashout=提现,transfer=转账,bonus=红利,other=其他
     * @param string $status  状态值|可选|:0=处理中,1=成功,2=失败
     * @param string $page  当前页数|可选
     */
    public function trade_log(){
        $page      = $this->input("page");
        $type      = $this->input("type");
        $status    = $this->input("status");
        $starttime = $this->input("starttime");
        $endtime = $this->input("endtime");
        if(!$starttime || !$endtime) return $this->error(__('请求参数不完整'));
        if($page <= 0) $page = 1;

        $where = " createtime between ".strtotime($starttime." 00:00:00")." AND ".strtotime($endtime." 23:59:59");
        $where .= " AND user_id='{$this->auth->id}' ";
        if($type)   $where .= " AND type='{$type}' ";
        if($status) $where .= " AND status='{$status}' "; 
       
        $data = TradeModel::log_list($where,$page);
        return $this->success(__('success'), $data);
    }


    /**
     * 充值金额列表
     * ApiMethod (POST)
     * @param string $paytype 支付方式|alipay:支付宝,wechat:微信,bank:银行转账
     */
    public function recharge_amount_list(){
        $paytype = $this->input("paytype");
        $payment_list = array_column(Config::get('Project.payment'), 'key');
        if(!in_array($paytype, $payment_list)) return $this->error(__('不支持的充值方式'));

        $list = [rand_amount(100), rand_amount(200), rand_amount(500), rand_amount(1000), rand_amount(5000), rand_amount(10000)];
        $range = ['100', '10009'];

        return $this->success(__('success'), ['list'=>$list,'range'=>$range]);
    }
    /**
     * 余额充值
     * ApiMethod (POST)
     * @param string $money   金额
     * @param string $paytype 支付方式|alipay:支付宝,wechat:微信,bank:银行转账
     * @param string $account 存款人名称|可选
     */
    public function recharge()
    {
        $money = $this->input("money");
        $paytype = $this->input("paytype");
        $account = $this->input("account");
        if(!$money || !$paytype) return $this->error(__('请求参数不完整'));
        // if($money < 1) return $this->error(__('金额不能小于1'));
        $payment_list = array_column(Config::get('Project.payment'), 'key');
        if(!in_array($paytype, $payment_list)) return $this->error(__('不支持的充值方式'));

        $count = TradeModel::name('trade_recharge')->where("user_id='{$this->auth->id}' AND status=0 AND createtime>='".strtotime("-2 minute")."'")->count();
        if($count >= 3) return $this->error(__('充值有问题，请联系在线客服'), '', -1001);

        //调用第三方支付链接(todo)...
        $platform_list = ['Daxiang', 'Qiyue'];
        $platform = 'Daxiang';
        // $platform = $platform_list[rand(0, count($platform_list)-1)];
        $cls_name = '\payment\\'.$platform;
        $paycls   = new $cls_name();

        $order_sn = order_sn();
        $pay_param = [
            'out_trade_no' => $order_sn,
            'paytype'      => $paytype,
            'amount'       => $money,
            'callback_url' => url('api/notify/recharge',   "payment={$platform}", '', true),
            'success_url'  => url('api/notify/pay_finish', "payment={$platform}", '', true),
            'error_url'    => url('api/notify/pay_finish', "payment={$platform}", '', true)
        ];
        $payinfo = $paycls->pay_url($pay_param);
        log_to(json_encode($pay_param)."\n".json_encode($payinfo), "tradeRecharge-{$platform}", '发起余额充值');
        if(!$payinfo || $payinfo['code'] != 1) return $this->error(__("充值通道维护中({$payinfo['msg']})..."));
        // if($paytype == 'alipay') $pay_url = $payinfo['alipay'];
        // if($paytype == 'wechat') $pay_url = $payinfo['wechat'];
        $pay_url = $payinfo['pay_url'];
        $out_trade_no = $payinfo['out_trade_no'];
        //生成充值订单
        $param = $this->request->param();
        $param['user_id'] = $this->auth->id;
        $param['order_sn'] = $order_sn;
        $param['out_trade_no'] = $out_trade_no;
        if(!TradeModel::recharge($param)) return $this->error(__('订单生成失败'));
        
        return $this->success(__('充值申请成功,请完成后续操作~'), ['pay_url'=>$pay_url]);
    }

    /**
     * 余额提现
     * ApiMethod (POST)
     * @param string $money   金额
     * @param string $bank_id 银行卡ID
     * @param string $paypass 取款密码
     */
    public function cashout()
    {
        $money = $this->input("money");
        $bank_id = $this->input("bank_id");
        $paypass = $this->input("paypass");

        $user_id = $this->auth->id;
        if(!$money || !$bank_id || $money<=0) return $this->error(__('请求参数不完整'));
        if($money > 50000) return $this->error(__('提款金额不能大于5万'));

        //登录太频繁限制
        $cashout_time = cache("cashoutTime:{$this->auth->id}");
        if($cashout_time>12) return $this->error(__('提现太频繁,请稍后操作'));
        cache("cashoutTime:{$this->auth->id}",$cashout_time+1, 60);

        $bank_info = db_get_row('user_bank',"id='{$bank_id}' AND user_id='{$user_id}'");
        if(!$bank_info) return $this->error(__('请先绑定银行卡'));
        if($money > $this->auth->money) return $this->error(__('提款金额不能大于中心钱包余额'));
        if($this->auth->getEncryptPassword($paypass) != $this->auth->paypass && !empty($paypass)) return $this->error(__('取款密码不正确'));

        //每日提现次数判断
        $day_timestamp = for_timestamp('day');
        $user_cashout_time = Db::name('trade_cashout')->where("createtime BETWEEN '{$day_timestamp['start']}' AND '{$day_timestamp['end']}' AND user_id='{$user_id}'")->count();
        $level_info = $user_info = Db::name('user u')->field('ul.day_cashout_time')->join('user_level ul', 'u.level=ul.id', 'LEFT')->where("u.id='{$user_id}'")->find();
        if($user_cashout_time >= $level_info['day_cashout_time']) return $this->error(__('今日提现次数已经用完，请明日再试'), '', -1001);

        $param = $this->request->param();
        $param['user_id'] = $user_id;
        $param = array_merge($param, $bank_info);
        if(!TradeModel::cashout($param)) return $this->error(__('提现失败'));
        return $this->success(__('提现申请成功,请耐心等待~'));
    }


}
